import os
import pandas as pd
from pyecharts.charts import Line
from pyecharts import options as opts
import webbrowser

# 所有区文件路径
folder = "data/"
files = [
    "北京昌平天气_2015_2025.xlsx", "北京朝阳天气_2015_2025.xlsx", "北京大兴天气_2015_2025.xlsx",
    "北京东城天气_2015_2025.xlsx", "北京房山天气_2015_2025.xlsx", "北京丰台天气_2015_2025.xlsx",
    "北京海淀天气_2015_2025.xlsx", "北京怀柔天气_2015_2025.xlsx", "北京门头沟天气_2015_2025.xlsx",
    "北京平谷天气_2015_2025.xlsx", "北京石景山天气_2015_2025.xlsx", "北京顺义天气_2015_2025.xlsx",
    "北京通州天气_2015_2025.xlsx", "北京西城天气_2015_2025.xlsx", "北京延庆天气_2015_2025.xlsx",
    "新北京密云天气_2015_2025.xlsx"
]
districts = [f.split("天气")[0].replace("新北京", "北京") for f in files]

# 每区每年AQI均值
result = {}
for file, district in zip(files, districts):
    path = os.path.join(folder, file)
    try:
        df = pd.read_excel(path)
        df['日期'] = pd.to_datetime(df['日期'].astype(str).str[:10], errors='coerce')
        df['year'] = df['日期'].dt.year

        # 拆分空气质量指数列（如 "84 良"）
        df[['AQI值', '等级']] = df['空气质量指数'].astype(str).str.extract(r'(\d+)\s*(\D*)')
        df['AQI值'] = pd.to_numeric(df['AQI值'], errors='coerce')

        df = df[df['year'].between(2020, 2024)]
        avg_aqi = df.groupby('year')['AQI值'].mean().round(2)
        result[district] = avg_aqi.to_dict()
    except Exception as e:
        print(f"{file} 处理失败: {e}")

# 转为 DataFrame
df_result = pd.DataFrame(result).T.fillna(0)
df_result = df_result[[2020, 2021, 2022, 2023, 2024]]  # 保证年份顺序

# 构建折线图
line = Line(init_opts=opts.InitOpts(width="1000px", height="520px"))
line.add_xaxis([str(y) for y in df_result.columns])

for district in df_result.index:
    line.add_yaxis(
        series_name=district,
        y_axis=df_result.loc[district].tolist(),
        is_smooth=True,
        label_opts=opts.LabelOpts(is_show=False)
    )

line.set_global_opts(
    title_opts=opts.TitleOpts(
        # title="2020–2024 年北京各区空气质量指数变化趋势",
        pos_left="center"
    ),
    xaxis_opts=opts.AxisOpts(name="年份"),
    yaxis_opts=opts.AxisOpts(
        name="AQI 指数",
        min_=45  # ✅ 设置最小值为45，压缩下方空间
    ),
    legend_opts=opts.LegendOpts(
        type_="scroll",
        orient="vertical",           # 垂直滚动
        pos_right="1%",              # 靠右
        pos_top="middle",            # 垂直居中
        item_width=14,
        item_height=14,
        textstyle_opts=opts.TextStyleOpts(font_size=12),
        page_button_gap=5,
        page_button_position="end"
    ),

    tooltip_opts=opts.TooltipOpts(trigger="axis")
)

# 输出网页
output_path = "beijing_aqi_trend_only_line.html"
line.render(output_path)
webbrowser.open(output_path)
